package cn.valo.basic.service.impl;

import cn.valo.basic.constants.BaseConstants;
import cn.valo.basic.dto.LoginDto;
import cn.valo.basic.dto.WeChatDto;
import cn.valo.basic.exception.BusinessException;
import cn.valo.basic.jwt.JwtUtils;
import cn.valo.basic.jwt.LoginResult;
import cn.valo.basic.jwt.Payload;
import cn.valo.basic.jwt.RsaUtils;
import cn.valo.basic.service.ILoginService;
import cn.valo.basic.util.AjaxResult;
import cn.valo.basic.util.HttpClientUtils;
import cn.valo.basic.util.MD5Utils;
import cn.valo.basic.util.StrUtils;
import cn.valo.system.domain.Menu;
import cn.valo.system.mapper.MenuMapper;
import cn.valo.system.mapper.PermissionMapper;
import cn.valo.user.domain.Logininfo;
import cn.valo.user.domain.User;
import cn.valo.user.domain.Wxuser;
import cn.valo.user.mapper.LogininfoMapper;
import cn.valo.user.mapper.UserMapper;
import cn.valo.user.mapper.WxuserMapper;
import cn.valo.user.service.impl.UserServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import java.util.HashMap;
import java.util.Map;
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserServiceImpl userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
     public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        //1.校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数必填！！");
        }
        //2.根据username + type 查询logininfo  要查询username phone email三个字段
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
        //2.1.查询不到... 报错
        if(logininfo == null){
            throw new BusinessException("账户不存在！！！");
        }
        //2.2 查到了，校验密码是否一致
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        if(!md5Pwd.equals(logininfo.getPassword())){
            //3.密码错误，报错
            throw new BusinessException("密码错误！！！");
        }
        //4.登录成功
//        //4.1 存储redis
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(
//                token,
//                logininfo,//对象要序列化
//                30,
//                TimeUnit.MINUTES
//        );
//        //4.2 返回token + logininfo
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//       //擦除敏感信息（密码，盐值）
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("logininfo",logininfo);
//        return map;
        //登陆成功调用loginSuccessHandler方法返回map，其中token为jwt串
    return loginSuccessHandler(logininfo);
    }
    /**
     * 处理登录成功之后的逻辑
     * @param logininfo
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //1.判断是否是员工吗，如果是员工，才需要查询权限
       if(logininfo.getType()==0){
           Long id = logininfo.getId();
           //获取权限
           List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(id);
           loginResult.setPermissions(permissions);
           //获取菜单
           List<Menu> menus=menuMapper.loadMenusByLogininfoId(id);
           loginResult.setMenus(menus);
       }
       //将登录人信息加密成jwt串
        //获取私钥
        String hrm_auth_rsa = JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile();
        PrivateKey privateKey = RsaUtils.getPrivateKey(hrm_auth_rsa);
        //使用私钥将loginResult加密成JWT串
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 30);
        //创建返回的map
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);//使用jwt串设置token
        //清楚敏感信息
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        return map;
    }
    //验证登陆状态
    @Override
    public  Map<String, Object> verify(String token) throws Exception{
        if(token==null){
            throw new BusinessException("token不能为null！");
        }
//        Object tokenValue = redisTemplate.opsForValue().get(token);
//        if(tokenValue==null){
//            throw new BusinessException("登陆已过期！");
//        }
//        String tokenTmp = String.valueOf(tokenValue);
//        String[] split = tokenTmp.split(",");
//        Map map = new HashMap();
//        map.put("username",split[0].substring(split[0].indexOf("=")+1));
//        map.put("phone",split[1].substring(split[1].indexOf("=")+1));
//        map.put("email",split[2].substring(split[2].indexOf("=")+1));
//        return map;
        //获取公钥
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
        //使用公钥解密token
        Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
        //获取登录人信息
        LoginResult loginResult = payload.getUserInfo();
        Logininfo logininfo = loginResult.getLogininfo();
        return loginSuccessHandler(logininfo);
    }

    @Override
    public AjaxResult wechat(WeChatDto dto) {
        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("code不能为空！！");
        }
        String tokenUrl = BaseConstants.WeChatConstants.TOKEN_URL.replace("APPID",BaseConstants.WeChatConstants.APPID)
                .replace("SECRET",BaseConstants.WeChatConstants.SECRET)
                .replace("CODE",code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
        Wxuser wxuser = wxuserMapper.queryByOpenId(openId);
        //已经绑定过账号直接登陆
//        if(wxuser !=null && wxuser.getUserId() != null){
//            User user = userMapper.queryById(wxuser.getUserId());
//            Logininfo logininfo = logininfoMapper.queryById(user.getLogininfoId());
//            String token = UUID.randomUUID().toString();
//            redisTemplate.opsForValue().set(
//                    token,
//                    logininfo,
//                    30,
//                    TimeUnit.MINUTES
//            );
//            //4.2 返回token + logininfo
//            Map<String, Object> map = new HashMap<>();
//            map.put("token",token);
//            //清楚敏感信息
//            logininfo.setSalt(null);
//            logininfo.setPassword(null);
//            map.put("logininfo",logininfo);
//            return AjaxResult.success().setResultObj(map);
//        }
        if(wxuser !=null && wxuser.getUserId() != null){
            User user = userMapper.queryById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.queryById(user.getLogininfoId());
            Map<String, Object> map = loginSuccessHandler(logininfo);
            return AjaxResult.success().setResultObj(map);

        }

        //没有绑定过账号绑定账号
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.error().setResultObj(binderParams);
    }
    @Override
    public Map<String, Object> binder(WeChatDto dto) {
//        1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.queryByPhone(dto.getPhone());
//        1.1 存在 查询出来，等着绑定
        Logininfo logininfo = null;
        if(user != null){
            logininfo = logininfoMapper.queryById(user.getLogininfoId());
        }else{
//        1.2 不存在 生成新的t_user + t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.insert(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        String wxUserUrl = BaseConstants.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
//        3.根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//        4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//        5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.insert(wxuser);
        Wxuser wxuser1 = wxuserMapper.queryByOpenId(wxuser.getOpenid());
        User user1 = userMapper.queryById(wxuser1.getUserId());
        user1.setUsername(wxuser1.getNickname());
        userMapper.update(user1);
//        6.直接免密登录
        //4.1 存储redis
        logininfo.setUsername(user1.getUsername());
       return loginSuccessHandler(logininfo);
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(
//                token,
//                logininfo,
//                30,
//                TimeUnit.MINUTES
//        );
//        //4.2 返回token + logininfo
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//
//        map.put("logininfo",logininfo);
//        return map;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User dto2User(WeChatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

}
